package com.whfc.common.aviator;

import com.alibaba.fastjson.JSON;
import com.googlecode.aviator.AviatorEvaluator;
import com.googlecode.aviator.runtime.type.AviatorFunction;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.HashMap;
import java.util.Map;

/**
 * @author sun_guodong
 * @description 表达式工具
 * @date 2020-12-09
 */
public class ValueCheckUtil {
    private static Logger logger = LoggerFactory.getLogger(ValueCheckUtil.class);

    /**
     * 检测报警值
     * ruleExpress :
     * machRotationCheck(rotationX,rotationZ,preRotationX,postRotationX,leftRotationZ,rightRotationZ)
     * speed>30
     * param :
     * {"rotationX":20,"rotationZ":30,"preRotationX":6,"postRotationX":6,"leftRotationZ":3,"rightRotationZ":10}
     * {"speed":20}
     *
     * @param function    自定义函数
     * @param ruleExpress 规则表达式
     * @param param       参数
     * @return
     */
    public static Object checkValue(AviatorFunction function, String ruleExpress, String param) {
        Map<String, Object> env = (Map) JSON.parse(param);
        if (function != null) {
            AviatorEvaluator.addFunction(function);
        }
        Object execute = AviatorEvaluator.execute(ruleExpress, env);
        return execute;
    }

    public static void main(String[] args) {
        // 常规
        String expression = "a-(b-c)>100";
        String param = "{\"a\":2,\"b\":2,\"c\":200}";
        Object o = checkValue(null, expression, param);
        System.out.println(o);

        // 倾斜角(自定义函数)
        String ruleExpress = "machRotationCheck(rotationX,rotationZ,preRotationX,postRotationX,leftRotationZ,rightRotationZ)";
        Map<String, Object> map = new HashMap<>();
        map.put("preRotationX", 1.0);
        map.put("postRotationX", 2.0);
        map.put("leftRotationZ", 3.0);
        map.put("rightRotationZ", 4.0);
        map.put("rotationX", 5.0);
        map.put("rotationZ", 7.0);
        Object o1 = checkValue(new MachRotationCheckFunction(), ruleExpress, JSON.toJSONString(map));
        System.out.println(o1);

        // 电子围栏
        String ruleExpress1 = "fenceCheck(preLat,preLng,curLat,curLng,type,radius,geometryWKT)";
        Map<String, Object> map1 = new HashMap<>();
        map1.put("preLat", 1.0);
        map1.put("preLng", 2.0);
        map1.put("curLat", 3.0);
        map1.put("curLng", 4.0);
        map1.put("type", 1);
        map1.put("radius", 7.0);
        map1.put("geometryWKT", " 7.0");
        Object o2 = checkValue(new FenceCheckFunction(), ruleExpress1, JSON.toJSONString(map1));
        System.out.println(o2);


    }

}
